/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jmail.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jmail.Config;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 *
 * @author iflamed
 */
public class Students {

    private File stuXml;
    private Document doc;
    private final static String FILEPATH = "\\students.xml";
    private File dirctory;

    public Students() {
        stuXml = new File(Config.getProps("jmail.dir") + FILEPATH);
        this.dirctory = new File(stuXml.getParent());
        try {
            this.createFile();
        } catch (IOException ex) {
            Logger.getLogger(Students.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JDOMException ex) {
            Logger.getLogger(Students.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void createFile() throws IOException, JDOMException {
        if (dirctory.exists()) {
            if (!stuXml.exists()) {
                stuXml.createNewFile();
                createXml();
            }
            System.out.println("文件创建成功:" + stuXml.getAbsolutePath());
        } else {
            dirctory.mkdirs();
            stuXml.createNewFile();
            createXml();
            System.out.println("文件创建成功：" + stuXml.getAbsolutePath());
        }
    }

    private void createXml() throws IOException {
        Element root = new Element("students");
        doc = new Document();
        doc.setRootElement(root);
        Format format = Format.getCompactFormat();
        format.setEncoding("GB2312"); //设置xml文件的字符为gb2312
        format.setIndent("    "); //设置xml文件的缩进为4个空格
        XMLOutputter XMLOut = new XMLOutputter(format);//元素后换行一层元素缩四格
        XMLOut.output(doc, new FileOutputStream(stuXml));
    }

    public boolean addStudent(String name, String stuNum, String totalscore,
            String assigncount, String detailfilepath) {
        try {
            Element root, student, stuName, stuNumber, totalScore, assignCount, detailfile;
            List<Element> students;
            SAXBuilder builder = new SAXBuilder();
            doc = builder.build(stuXml);
            root = doc.getRootElement();
            students = root.getChildren();
            Iterator it = students.iterator();
            while (it.hasNext()) {
                student = (Element) it.next();
                if (student.getChild("studentNumber").getText().equals(stuNum)) {
                    return false;
                }
            }
            student = new Element("student");
            stuName = new Element("studentName");
            stuName.setText(name);
            stuNumber = new Element("studentNumber");
            stuNumber.setText(stuNum);
            totalScore = new Element("totalscore");
            totalScore.setText(totalscore);
            assignCount = new Element("assigncount");
            assignCount.setText(assigncount);
            detailfile = new Element("detailfilepath");
            detailfile.setText(Config.getProps("jmail.dir")+detailfilepath);
            student.addContent(stuName);
            student.addContent(stuNumber);
            student.addContent(totalScore);
            student.addContent(assignCount);
            student.addContent(detailfile);
            root.addContent(student);
            Format format = Format.getCompactFormat();
            format.setEncoding("GB2312"); //设置xml文件的字符为gb2312
            format.setIndent("    "); //设置xml文件的缩进为4个空格
            XMLOutputter outputter = new XMLOutputter(format);
            outputter.output(doc, new FileOutputStream(stuXml));
            return true;
        } catch (JDOMException ex) {
            Logger.getLogger(Students.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (IOException ex) {
            Logger.getLogger(Students.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    /**
     *
     * @param number Student card number <String>
     * @param attr the element need to update <String>
     * @param value the elment value <String>
     * @return
     */
    public boolean updateStudent(String number, String attr, String value) {
        try {
            Element root, student;
            List<Element> students;
            SAXBuilder builder = new SAXBuilder();
            doc = builder.build(stuXml);
            root = doc.getRootElement();
            students = root.getChildren();
            Iterator it = students.iterator();
            while (it.hasNext()) {
                student = (Element) it.next();
                if (student.getChild("studentNumber").getText().equals(number)) {
                    student.getChild(attr).setText(value);
                    break;
                }
            }
            Format format = Format.getCompactFormat();
            format.setEncoding("GB2312"); //设置xml文件的字符为gb2312
            format.setIndent("    "); //设置xml文件的缩进为4个空格
            XMLOutputter outputter = new XMLOutputter(format);
            outputter.output(doc, new FileOutputStream(stuXml));
            return true;
        } catch (JDOMException ex) {
            Logger.getLogger(Students.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (IOException ex) {
            Logger.getLogger(Students.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    private boolean userExists(String number) {
        try {
            Element root, student;
            List<Element> students;
            SAXBuilder builder = new SAXBuilder();
            doc = builder.build(stuXml);
            root = doc.getRootElement();
            students = root.getChildren();
            Iterator it = students.iterator();
            while (it.hasNext()) {
                student = (Element) it.next();
                if (student.getChild("studentNumber").getText().equals(number)) {
                    return false;
                }
            }
            return true;
        } catch (JDOMException ex) {
            Logger.getLogger(Students.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (IOException ex) {
            Logger.getLogger(Students.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    public int getAssginCount(String number) {
        try {
            Element root, student;
            List<Element> students;
            SAXBuilder builder = new SAXBuilder();
            doc = builder.build(stuXml);
            root = doc.getRootElement();
            students = root.getChildren();
            Iterator it = students.iterator();
            while (it.hasNext()) {
                student = (Element) it.next();
                if (student.getChild("studentNumber").getText().equals(number)) {
                    return Integer.parseInt(student.getChildText("assigncount"));
                }
            }
            return 0;
        } catch (JDOMException ex) {
            Logger.getLogger(Students.class.getName()).log(Level.SEVERE, null, ex);
            return 0;
        } catch (IOException ex) {
            Logger.getLogger(Students.class.getName()).log(Level.SEVERE, null, ex);
            return 0;
        }
    }
    public List getAllStudents(){
        try {
            Element root;
            List<Element> students;
            SAXBuilder builder = new SAXBuilder();
            doc = builder.build(stuXml);
            root = doc.getRootElement();
            students = root.getChildren();
            return students;
        } catch (JDOMException ex) {
            Logger.getLogger(Students.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (IOException ex) {
            Logger.getLogger(Students.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
}
